home *** CD-ROM | disk | FTP | other *** search
/ Almathera Ten Pack 1: Comms & Networking / Almathera Ten on Ten - Disc 1: Comms & Networking.iso / amiga-useful / perl / faq / 4.5_generalprogramming < prev    next >
Encoding:
Text File  |  1995-05-04  |  36.8 KB  |  1,136 lines

  1. Newsgroups: comp.lang.perl,comp.answers,news.answers
  2. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!hookup!news.sprintlink.net!ddi2.digital.net!vx!usenet!spp
  3. From: spp@vx.com
  4. Subject: comp.lang.perl FAQ 4/5 - General Programming
  5. Message-ID: <SPP.95Apr4141315@squid.vx.com>
  6. Followup-To: poster
  7. Sender: usenet@vx.com
  8. Nntp-Posting-Host: squid
  9. Organization: Varimetrix Corporation
  10. Date: Tue, 4 Apr 1995 18:13:15 GMT
  11. Approved: news-answers-request@MIT.EDU
  12. Lines: 1121
  13. Xref: senator-bedfellow.mit.edu comp.lang.perl:47092 comp.answers:11038 news.answers:41335
  14.  
  15. Archive-name: perl-faq/part4
  16. Version: $Id: part4,v 2.7 1995/04/04 16:40:28 spp Exp spp $
  17. Posting-Frequency: bi-weekly
  18. Change-Log: $Log: part4,v $
  19. # Revision 2.7  1995/04/04  16:40:28  spp
  20. # 03/23/95 -  Updated 4.3 (my vs local) to have a better example
  21. # 03/23/95 -  Changed wording on Question 4.20
  22. #
  23. # Revision 2.6  1995/03/17  16:47:55  spp
  24. # 03/07/95 -  Corrected numbering error
  25. #
  26. # Revision 2.5  1995/01/31  14:45:52  spp
  27. # 12/07/94 -  Changed 4.29 to reflect reality as blessed by Randal. ;-)
  28. # 12/13/94 -  Modified question referencing perl-byacc to point to the
  29. #             perl-byacc question in part 3.
  30. # 01/23/95 -  Fixed typos and modified blank-stripping question as discussed
  31. #             by Jeffrey Friedl.
  32. # 01/31/95 -  Modified (no)echo and single-reading to include
  33. #             Curses::(no){cbreak, echo}.
  34. #
  35.  
  36.  
  37. This posting contains answers to the following questions about General
  38. Programming, Regular Expressions (Regexp) and Input/Output:
  39.  
  40.  
  41. 4.1) What are all these $@%*<> signs and how do I know when to use them?
  42.  
  43.     Those are type specifiers: 
  44.     $ for scalar values
  45.     @ for indexed arrays
  46.     % for hashed arrays (associative arrays)
  47.     * for all types of that symbol name.  These are sometimes used like
  48.         pointers
  49.     <> are used for inputting a record from a filehandle.  
  50.  
  51.     See the question on arrays of arrays for more about Perl pointers.
  52.  
  53.     While there are a few places where you don't actually need these type
  54.     specifiers, except for files, you should always use them.  Note that
  55.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  56.     getline function, that is, it reads a line from the handle FILE.  When
  57.     doing open, close, and other operations besides the getline function on
  58.     files, do NOT use the brackets.
  59.  
  60.     Beware of saying:
  61.     $foo = BAR;
  62.     Which wil be interpreted as 
  63.     $foo = 'BAR';
  64.     and not as 
  65.     $foo = <BAR>;
  66.     If you always quote your strings, you'll avoid this trap.
  67.  
  68.     Normally, files are manipulated something like this (with appropriate
  69.     error checking added if it were production code):
  70.  
  71.     open (FILE, ">/tmp/foo.$$");
  72.     print FILE "string\n";
  73.     close FILE;
  74.  
  75.     If instead of a filehandle, you use a normal scalar variable with file
  76.     manipulation functions, this is considered an indirect reference to a
  77.     filehandle.  For example,
  78.  
  79.     $foo = "TEST01";
  80.     open($foo, "file");
  81.  
  82.     After the open, these two while loops are equivalent:
  83.  
  84.     while (<$foo>) {}
  85.     while (<TEST01>) {}
  86.  
  87.     as are these two statements:
  88.     
  89.     close $foo;
  90.     close TEST01;
  91.  
  92.     but NOT to this:
  93.  
  94.     while (<$TEST01>) {} # error
  95.         ^
  96.         ^ note spurious dollar sign
  97.  
  98.     This is another common novice mistake; often it's assumed that
  99.  
  100.     open($foo, "output.$$");
  101.  
  102.     will fill in the value of $foo, which was previously undefined.  This
  103.     just isn't so -- you must set $foo to be the name of a filehandle
  104.     before you attempt to open it.   
  105.  
  106.  
  107. 4.2) How come Perl operators have different precedence than C operators?
  108.  
  109.     Actually, they don't; all C operators have the same precedence in Perl as
  110.     they do in C.  The problem is with a class of functions called list
  111.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  112.     bizarre in that they have different precedence depending on whether you
  113.     look on the left or right of them.  Basically, they gobble up all things
  114.     on their right.  For example,
  115.  
  116.     unlink $foo, "bar", @names, "others";
  117.  
  118.     will unlink all those file names.  A common mistake is to write:
  119.  
  120.     unlink "a_file" || die "snafu";
  121.  
  122.     The problem is that this gets interpreted as
  123.  
  124.     unlink("a_file" || die "snafu");
  125.  
  126.     To avoid this problem, you can always make them look like function calls
  127.     or use an extra level of parentheses:
  128.  
  129.     unlink("a_file")  || die "snafu";
  130.     (unlink "a_file") || die "snafu";
  131.  
  132.     In perl5, there are low precedence "and", "or", and "not" operators,
  133.     which bind less tightly than comma.  This allows you to write:
  134.  
  135.     unlink $foo, "bar", @names, "others"     or die "snafu";
  136.  
  137.     Sometimes you actually do care about the return value:
  138.  
  139.     unless ($io_ok = print("some", "list")) { } 
  140.  
  141.     Yes, print() returns I/O success.  That means
  142.  
  143.     $io_ok = print(2+4) * 5;
  144.  
  145.     returns 5 times whether printing (2+4) succeeded, and 
  146.     print(2+4) * 5;
  147.     returns the same 5*io_success value and tosses it.
  148.  
  149.     See the perlop(1) man page's section on Precedence for more gory details,
  150.     and be sure to use the -w flag to catch things like this.
  151.  
  152.  
  153. 4.3) What's the difference between dynamic and static (lexical) scoping?
  154.      What are my() and local()?
  155.  
  156.     [NOTE: This question refers to perl5 only.  There is no my() in perl4]
  157.     Scoping refers to visibility of variables.  A dynamic variable is
  158.     created via local() and is just a local value for a global variable,
  159.     whereas a lexical variable created via my() is more what you're
  160.     expecting from a C auto.  (See also "What's the difference between
  161.     deep and shallow binding.")  In general, we suggest you use lexical
  162.     variables wherever possible, as they're faster to access and easier to
  163.     understand.   The "use strict vars" pragma will enforce that all
  164.     variables are either lexical, or full classified by package name.  We
  165.     strongly suggest that you develop your code with "use strict;" and the
  166.     -w flag.  (When using formats, however, you will still have to use
  167.     dynamic variables.)  Here's an example of the difference:
  168.  
  169.         #!/usr/local/bin/perl
  170.         $myvar = 10;
  171.         $localvar = 10;
  172.  
  173.         print "Before the sub call - my: $myvar, local: $localvar\n";
  174.         &sub1();
  175.  
  176.         print "After the sub call - my: $myvar, local: $localvar\n";
  177.  
  178.         exit(0);
  179.  
  180.         sub sub1 {
  181.             my $myvar;
  182.             local $localvar;
  183.  
  184.             $myvar = 5;     # Only in this block
  185.             $localvar = 20; # Accessible to children
  186.  
  187.             print "Inside first sub call - my: $myvar, local: $localvar\n";
  188.  
  189.             &sub2();
  190.         }
  191.  
  192.         sub sub2 {
  193.             print "Inside second sub - my: $myvar, local: $localvar\n";
  194.         }
  195.  
  196.     Notice that the variables declared with my() are visible only within
  197.     the scope of the block which names them.  They are not visible outside
  198.     of this block, not even in routines or blocks that it calls.  local() 
  199.     variables, on the other hand, are visible to routines that are called
  200.     from the block where they are declared.  Neither is visible after the
  201.     end (the final closing curly brace) of the block at all.
  202.  
  203.     Oh, lexical variables are only available in perl5.  Have we
  204.     mentioned yet that you might consider upgrading? :-)
  205.  
  206.  
  207. 4.4) What's the difference between deep and shallow binding?
  208.  
  209.     This only matters when you're making subroutines yourself, at least
  210.     so far.   This will give you shallow binding:
  211.  
  212.     {
  213.           my $x = time;
  214.           $coderef = sub { $x };
  215.         }
  216.  
  217.     When you call &$coderef(), it will get whatever dynamic $x happens
  218.     to be around when invoked.  However, you can get the other behaviour
  219.     this way:
  220.  
  221.     {
  222.           my $x = time;
  223.           $coderef = eval "sub { \$x }";
  224.         }
  225.  
  226.     Now you'll access the lexical variable $x which is set to the
  227.     time the subroutine was created.  Note that the difference in these
  228.     two behaviours can be considered a bug, not a feature, so you should
  229.     in particular not rely upon shallow binding, as it will likely go
  230.     away in the future.  See perlref(1).
  231.  
  232.  
  233. 4.5) How can I manipulate fixed-record-length files?
  234.  
  235.     The most efficient way is using pack and unpack.  This is faster than
  236.     using substr.  Here is a sample chunk of code to break up and put back
  237.     together again some fixed-format input lines, in this case, from ps.
  238.  
  239.     # sample input line:
  240.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  241.     $ps_t = 'A6 A4 A7 A5 A*';
  242.     open(PS, "ps|");
  243.     $_ = <PS>; print;
  244.     while (<PS>) {
  245.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  246.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  247.         print "$var: <", eval "\$$var", ">\n";
  248.         }
  249.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  250.     }
  251.  
  252.  
  253. 4.6) How can I make a file handle local to a subroutine?
  254.  
  255.     You must use the type-globbing *VAR notation.  Here is some code to
  256.     cat an include file, calling itself recursively on nested local
  257.     include files (i.e. those with #include "file", not #include <file>):
  258.  
  259.     sub cat_include {
  260.         local($name) = @_;
  261.         local(*FILE);
  262.         local($_);
  263.  
  264.         warn "<INCLUDING $name>\n";
  265.         if (!open (FILE, $name)) {
  266.         warn "can't open $name: $!\n";
  267.         return;
  268.         }
  269.         while (<FILE>) {
  270.         if (/^#\s*include "([^"]*)"/) {
  271.             &cat_include($1);
  272.         } else {
  273.             print;
  274.         }
  275.         }
  276.         close FILE;
  277.     }
  278.  
  279.  
  280. 4.7) How can I call alarm() or usleep() from Perl?
  281.  
  282.     If you want finer granularity than 1 second (as usleep() provides) and
  283.     have itimers and syscall() on your system, you can use the following.
  284.     You could also use select().
  285.  
  286.     It takes a floating-point number representing how long to delay until
  287.     you get the SIGALRM, and returns a floating- point number representing
  288.     how much time was left in the old timer, if any.  Note that the C
  289.     function uses integers, but this one doesn't mind fractional numbers.
  290.  
  291.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  292.     # tom christiansen <tchrist@convex.com>
  293.     sub alarm {
  294.     require 'syscall.ph';
  295.     require 'sys/time.ph';
  296.  
  297.     local($ticks) = @_;
  298.     local($in_timer,$out_timer);
  299.     local($isecs, $iusecs, $secs, $usecs);
  300.  
  301.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  302.  
  303.     $secs = int($ticks);
  304.     $usecs = ($ticks - $secs) * 1e6;
  305.  
  306.     $out_timer = pack($itimer_t,0,0,0,0);  
  307.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  308.  
  309.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  310.         && die "alarm: setitimer syscall failed: $!";
  311.  
  312.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  313.     return $secs + ($usecs/1e6);
  314.     }
  315.  
  316.  
  317. 4.8) How can I do an atexit() or setjmp()/longjmp() in Perl?  (Exception handling)
  318.  
  319.     Perl's exception-handling mechanism is its eval operator.  You 
  320.     can use eval as setjmp and die as longjmp.  Here's an example
  321.     of Larry's for timed-out input, which in C is often implemented
  322.     using setjmp and longjmp:
  323.  
  324.       $SIG{ALRM} = TIMEOUT;
  325.       sub TIMEOUT { die "restart input\n" }
  326.  
  327.       do { eval { &realcode } } while $@ =~ /^restart input/;
  328.  
  329.       sub realcode {
  330.           alarm 15;
  331.           $ans = <STDIN>;
  332.           alarm 0;
  333.       }
  334.  
  335.    Here's an example of Tom's for doing atexit() handling:
  336.  
  337.     sub atexit { push(@_exit_subs, @_) }
  338.  
  339.     sub _cleanup { unlink $tmp }
  340.  
  341.     &atexit('_cleanup');
  342.  
  343.     eval <<'End_Of_Eval';  $here = __LINE__;
  344.     # as much code here as you want
  345.     End_Of_Eval
  346.  
  347.     $oops = $@;  # save error message
  348.  
  349.     # now call his stuff
  350.     for (@_exit_subs) { &$_() }
  351.  
  352.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  353.         " line " . ($1+$here)/e, die $oops);
  354.  
  355.     You can register your own routines via the &atexit function now.  You
  356.     might also want to use the &realcode method of Larry's rather than
  357.     embedding all your code in the here-is document.  Make sure to leave
  358.     via die rather than exit, or write your own &exit routine and call
  359.     that instead.   In general, it's better for nested routines to exit
  360.     via die rather than exit for just this reason.
  361.  
  362.     In Perl5, it is easy to set this up because of the automatic processing
  363.     of per-package END functions. 
  364.  
  365.     Eval is also quite useful for testing for system dependent features,
  366.     like symlinks, or using a user-input regexp that might otherwise
  367.     blowup on you.
  368.  
  369.  
  370. 4.9) How do I catch signals in perl?
  371.  
  372.     Perl allows you to trap signals using the %SIG associative array.
  373.     Using the signals you want to trap as the key, you can assign a
  374.     subroutine to that signal.  The %SIG array will only contain those
  375.     values which the programmer defines.  Therefore, you do not have to
  376.     assign all signals.  For example, to exit cleanly from a ^C:
  377.  
  378.     $SIG{'INT'} = 'CLEANUP';
  379.     sub CLEANUP {
  380.         print "\n\nCaught Interrupt (^C), Aborting\n";
  381.         exit(1);
  382.     }
  383.  
  384.     There are two special "routines" for signals called DEFAULT and IGNORE.
  385.     DEFAULT erases the current assignment, restoring the default value of
  386.     the signal.  IGNORE causes the signal to be ignored.  In general, you
  387.     don't need to remember these as you can emulate their functionality
  388.     with standard programming features.  DEFAULT can be emulated by
  389.     deleting the signal from the array and IGNORE can be emulated by any
  390.     undeclared subroutine.
  391.  
  392. 4.10) Why doesn't Perl interpret my octal data octally?
  393.  
  394.     Perl only understands octal and hex numbers as such when they occur
  395.     as literals in your program.  If they are read in from somewhere and
  396.     assigned, then no automatic conversion takes place.  You must
  397.     explicitly use oct() or hex() if you want this kind of thing to happen. 
  398.     Actually, oct() knows to interpret both hex and octal numbers, while
  399.     hex only converts hexadecimal ones.  For example:
  400.  
  401.     {
  402.         print "What mode would you like? ";
  403.         $mode = <STDIN>;
  404.         $mode = oct($mode);
  405.         unless ($mode) {
  406.         print "You can't really want mode 0!\n";
  407.         redo;
  408.         } 
  409.         chmod $mode, $file;
  410.     } 
  411.  
  412.     Without the octal conversion, a requested mode of 755 would turn 
  413.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  414.  
  415.     If you want something that handles decimal, octal and hex input, 
  416.     you could follow the suggestion in the man page and use:
  417.  
  418.     $val = oct($val) if $val =~ /^0/;
  419.  
  420.  
  421. 4.11) How can I compare two date strings?
  422.  
  423.     If the dates are in an easily parsed, predetermined format, then you
  424.     can break them up into their component parts and call &timelocal from
  425.     the distributed perl library.  If the date strings are in arbitrary
  426.     formats, however, it's probably easier to use the getdate program from
  427.     the Cnews distribution, since it accepts a wide variety of dates.  Note
  428.     that in either case the return values you will really be comparing will
  429.     be the total time in seconds as returned by time(). 
  430.    
  431.     Here's a getdate function for perl that's not very efficient; you can
  432.     do better than this by sending it many dates at once or modifying
  433.     getdate to behave better on a pipe.  Beware the hardcoded pathname. 
  434.  
  435.     sub getdate {
  436.         local($_) = shift;
  437.  
  438.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  439.         # getdate has broken timezone sign reversal!
  440.  
  441.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  442.         chop;
  443.         $_;
  444.     } 
  445.  
  446.     Richard Ohnemus <Rick_Ohnemus@Sterling.COM> actually has a getdate.y for
  447.     use with the Perl yacc (see question 3.3 "Is there a yacc for Perl?").  
  448.  
  449.     You might also consider using these: 
  450.  
  451.     date.pl        - print dates how you want with the sysv +FORMAT method 
  452.     date.shar      - routines to manipulate and calculate dates
  453.     ftp-chat2.shar - updated version of ftpget. includes library and demo 
  454.              programs 
  455.     getdate.shar   - returns number of seconds since epoch for any given
  456.              date 
  457.     ptime.shar     - print dates how you want with the sysv +FORMAT method 
  458.  
  459.     You probably want 'getdate.shar'... these and other files can be ftp'd
  460.     from the /pub/perl/scripts directory on ftp.cis.ufl.edu. See the README
  461.     file in the /pub/perl directory for time and the European mirror site
  462.     details. 
  463.  
  464.  
  465. 4.12) How can I find the Julian Day?
  466.  
  467.     Here's an example of a Julian Date function provided by Thomas R.
  468.     Kimpton*.
  469.  
  470.     #!/usr/local/bin/perl
  471.  
  472.     @theJulianDate = ( 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 );
  473.  
  474.     #************************************************************************
  475.     #****   Return 1 if we are after the leap day in a leap year.       *****
  476.     #************************************************************************
  477.                    
  478.     sub leapDay             
  479.     {                 
  480.         my($year,$month,$day) = @_;
  481.     
  482.         if (year % 4) {
  483.         return(0);
  484.         }
  485.  
  486.         if (!(year % 100)) {             # years that are multiples of 100
  487.                                      # are not leap years
  488.         if (year % 400) {            # unless they are multiples of 400
  489.             return(0);
  490.         }
  491.         }
  492.         if (month < 2) {
  493.             return(0);
  494.         } elsif ((month == 2) && (day < 29)) {
  495.         return(0);
  496.         } else {
  497.         return(1);
  498.         }
  499.     }
  500.     
  501.     #************************************************************************
  502.     #****   Pass in the date, in seconds, of the day you want the       *****
  503.     #****   julian date for.  If your localtime() returns the year day  *****
  504.     #****   return that, otherwise figure out the julian date.          *****
  505.     #************************************************************************
  506.         
  507.     sub julianDate    
  508.     {        
  509.         my($dateInSeconds) = @_;
  510.         my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday);
  511.     
  512.         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) =
  513.         localtime($dateInSeconds);
  514.         if (defined($yday)) {
  515.         return($yday+1);
  516.         } else {
  517.         return($theJulianDate[$mon] + $mday + &leapDay($year,$mon,$mday));
  518.         }
  519.     
  520.     }
  521.  
  522.     print "Today's julian date is: ",&julianDate(time),"\n";
  523.  
  524.  
  525. 4.13) What's the fastest way to code up a given task in perl?
  526.  
  527.     Post it to comp.lang.perl and ask Tom or Randal a question about it.
  528.     ;) 
  529.  
  530.     Because Perl so lends itself to a variety of different approaches for
  531.     any given task, a common question is which is the fastest way to code a
  532.     given task.  Since some approaches can be dramatically more efficient
  533.     that others, it's sometimes worth knowing which is best.
  534.     Unfortunately, the implementation that first comes to mind, perhaps as
  535.     a direct translation from C or the shell, often yields suboptimal
  536.     performance.  Not all approaches have the same results across different
  537.     hardware and software platforms.  Furthermore, legibility must
  538.     sometimes be sacrificed for speed. 
  539.  
  540.     While an experienced perl programmer can sometimes eye-ball the code
  541.     and make an educated guess regarding which way would be fastest,
  542.     surprises can still occur.  So, in the spirit of perl programming
  543.     being an empirical science, the best way to find out which of several
  544.     different methods runs the fastest is simply to code them all up and
  545.     time them. For example:
  546.  
  547.     $COUNT = 10_000; $| = 1;
  548.  
  549.     print "method 1: ";
  550.  
  551.         ($u, $s) = times;
  552.         for ($i = 0; $i < $COUNT; $i++) {
  553.         # code for method 1
  554.         }
  555.         ($nu, $ns) = times;
  556.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  557.  
  558.     print "method 2: ";
  559.  
  560.         ($u, $s) = times;
  561.         for ($i = 0; $i < $COUNT; $i++) {
  562.         # code for method 2
  563.         }
  564.         ($nu, $ns) = times;
  565.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  566.  
  567.     Perl5 includes a new module called Benchmark.pm.  You can now simplify
  568.     the code to use the Benchmarking, like so:
  569.  
  570.         use Benchmark;
  571.  
  572.             timethese($count, {
  573.                 Name1 => '...code for method 1...',
  574.                 Name2 => '...code for method 2...',
  575.                 ... });
  576.  
  577.     It will output something that looks similar to this:
  578.  
  579.         Benchmark: timing 100 iterations of Name1, Name2...
  580.                 Name1:  2 secs (0.50 usr 0.00 sys = 0.50 cpu)
  581.                 Name2:  1 secs (0.48 usr 0.00 sys = 0.48 cpu)
  582.  
  583.  
  584.     For example, the following code will show the time difference between
  585.     three different ways of assigning the first character of a string to
  586.     a variable:
  587.  
  588.     use Benchmark;
  589.     timethese(100000, {
  590.         'regex1' => '$str="ABCD"; $str =~ s/^(.)//; $ch = $1',
  591.         'regex2' => '$str="ABCD"; $str =~ s/^.//; $ch = $&',
  592.         'substr' => '$str="ABCD"; $ch=substr($str,0,1); substr($str,0,1)="",
  593.     });
  594.  
  595.     The results will be returned like this:
  596.  
  597.     Benchmark: timing 100000 iterations of regex1, regex2, substr...
  598.        regex1: 11 secs (10.80 usr   0.00 sys =  10.80 cpu)
  599.        regex2: 10 secs (10.23 usr   0.00 sys =  10.23 cpu)
  600.        substr:  7 secs ( 5.62 usr    0.00 sys =   5.62 cpu)
  601.  
  602.     For more specific tips, see the section on Efficiency in the
  603.     ``Other Oddments'' chapter at the end of the Camel Book.
  604.  
  605.  
  606. 4.14) Do I always/never have to quote my strings or use semicolons?
  607.  
  608.     You don't have to quote strings that can't mean anything else in the
  609.     language, like identifiers with any upper-case letters in them.
  610.     Therefore, it's fine to do this: 
  611.  
  612.     $SIG{INT} = Timeout_Routine;
  613.     or 
  614.  
  615.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  616.  
  617.     but you can't get away with this:
  618.  
  619.     $foo{while} = until;
  620.  
  621.     in place of 
  622.  
  623.     $foo{'while'} = 'until';
  624.  
  625.     The requirements on semicolons have been increasingly relaxed.  You no 
  626.     longer need one at the end of a block, but stylistically, you're better
  627.     to use them if you don't put the curly brace on the same line: 
  628.  
  629.     for (1..10) { print }
  630.  
  631.     is ok, as is
  632.  
  633.     @nlist = sort { $a <=> $b } @olist;
  634.  
  635.     but you probably shouldn't do this:
  636.     
  637.     for ($i = 0; $i < @a; $i++) {
  638.         print "i is $i\n"  # <-- oops!
  639.     } 
  640.  
  641.     because you might want to add lines later, and anyway, it looks
  642.     funny. :-) 
  643.  
  644.  
  645. 4.15) What is variable suicide and how can I prevent it?
  646.  
  647.     Variable suicide is a nasty side effect of dynamic scoping and the way
  648.     variables are passed by reference.  If you say 
  649.  
  650.     $x = 17;
  651.     &munge($x);
  652.     sub munge {
  653.         local($x);
  654.         local($myvar) = $_[0];
  655.         ...
  656.     } 
  657.  
  658.     Then you have just clobbered $_[0]!  Why this is occurring is pretty
  659.     heavy wizardry: the reference to $x stored in $_[0] was temporarily
  660.     occluded by the previous local($x) statement (which, you're recall,
  661.     occurs at run-time, not compile-time).  The work around is simple,
  662.     however: declare your formal parameters first:
  663.  
  664.     sub munge {
  665.         local($myvar) = $_[0];
  666.         local($x);
  667.         ...
  668.     }
  669.  
  670.     That doesn't help you if you're going to be trying to access @_
  671.     directly after the local()s.  In this case, careful use of the package
  672.     facility is your only recourse. 
  673.  
  674.     Another manifestation of this problem occurs due to the magical nature
  675.     of the index variable in a foreach() loop. 
  676.  
  677.     @num = 0 .. 4;
  678.     print "num begin  @num\n";
  679.     foreach $m (@num) { &ug }
  680.     print "num finish @num\n";
  681.     sub ug {
  682.         local($m) = 42;
  683.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  684.     }
  685.     
  686.     Which prints out the mysterious:
  687.  
  688.     num begin  0 1 2 3 4
  689.     m=42  42,1,2,3
  690.     m=42  0,42,2,3
  691.     m=42  0,1,42,3
  692.     m=42  0,1,2,42
  693.     m=42  0,1,2,3
  694.     num finish 0 1 2 3 4
  695.  
  696.     What's happening here is that $m is an alias for each element of @num.
  697.     Inside &ug, you temporarily change $m.  Well, that means that you've
  698.     also temporarily changed whatever $m is an alias to!!  The only
  699.     workaround is to be careful with global variables, using packages,
  700.     and/or just be aware of this potential in foreach() loops. 
  701.  
  702.     The perl5 static autos via "my" do not exihibit this problem.
  703.  
  704.  
  705. 4.16) What does "Malformed command links" mean?
  706.  
  707.     This is a bug in 4.035.  While in general it's merely a cosmetic
  708.     problem, it often comanifests with a highly undesirable coredumping 
  709.     problem.  Programs known to be affected by the fatal coredump include
  710.     plum and pcops.  This bug has been fixed since 4.036.  It did not
  711.     resurface in 5.001.
  712.  
  713.  
  714. 4.17) How can I set up a footer format to be used with write()?
  715.  
  716.     While the $^ variable contains the name of the current header format,
  717.     there is no corresponding mechanism to automatically do the same thing
  718.     for a footer.  Not knowing how big a format is going to be until you
  719.     evaluate it is one of the major problems.
  720.  
  721.     If you have a fixed-size footer, you can get footers by checking for
  722.     line left on page ($-) before each write, and printing the footer
  723.     yourself if necessary.
  724.  
  725.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  726.     and always write()ing to the KID, who then postprocesses its STDIN to
  727.     rearrange headers and footers however you like.  Not very convenient,
  728.     but doable.
  729.  
  730.  
  731. 4.18) Why does my Perl program keep growing in size?
  732.  
  733.     This is caused by a strange occurance that Larry has dubbed "feeping
  734.     creaturism".  Larry is always adding one more feature, always getting
  735.     Perl to handle one more problem.  Hence, it keeps growing.  Once you've
  736.     worked with perl long enough, you will probably start to do the same
  737.     thing.  You will then notice this problem as you see your scripts
  738.     becoming larger and larger.
  739.  
  740.     Oh, wait... you meant a currently running program and it's stack size.
  741.     Mea culpa, I misunderstood you.  ;)  While there may be a real memory
  742.     leak in the Perl source code or even whichever malloc() you're using,
  743.     common causes are incomplete eval()s or local()s in loops.
  744.  
  745.     An eval() which terminates in error due to a failed parsing will leave
  746.     a bit of memory unusable. 
  747.  
  748.     A local() inside a loop:
  749.  
  750.     for (1..100) {
  751.         local(@array);
  752.     } 
  753.  
  754.     will build up 100 versions of @array before the loop is done.  The
  755.     work-around is:   
  756.  
  757.     local(@array);
  758.     for (1..100) {
  759.         undef @array;
  760.     } 
  761.  
  762.     Larry reports that this behavior is fixed for perl5.
  763.  
  764.  
  765. 4.19) Can I do RPC in Perl?
  766.  
  767.     Yes, you can, since Perl has access to sockets.  An example of the rup
  768.     program written in Perl can be found in the script ruptime.pl at the
  769.     scripts archive on ftp.cis.ufl.edu.  I warn you, however, that it's not
  770.     a pretty sight, as it's used nothing from h2ph or c2ph, so everything is
  771.     utterly hard-wired. 
  772.  
  773.  
  774. 4.20) Why doesn't my sockets program work under System V (Solaris)?
  775.  
  776.     For some strange and unknown reason, some of the socket constants have
  777.     been changed in Solaris.  What is probably causing your problems is
  778.     that SOCK_STEAM now has a value of 2, whereas SunOS 4.X uses a value of
  779.     1.  Instead of hardcoding this value, you should require Sockets and
  780.     use SOCK_STREAM.
  781.  
  782.  
  783. 4.21) How can I quote a variable to use in a regexp?
  784.  
  785.     From the manual:
  786.  
  787.     $pattern =~ s/(\W)/\\$1/g;
  788.  
  789.     Now you can freely use /$pattern/ without fear of any unexpected meta-
  790.     characters in it throwing off the search.  If you don't know whether a
  791.     pattern is valid or not, enclose it in an eval to avoid a fatal run-
  792.     time error.  
  793.  
  794.     Perl5 provides a vastly improved way of doing this.  Simply use the
  795.     new quotemeta character (\Q) within your variable.
  796.  
  797. 4.22) How can I change the first N letters of a string?
  798.  
  799.     Remember that the substr() function produces an lvalue, that is, it may
  800.     be assigned to.  Therefore, to change the first character to an S, you
  801.     could do this:
  802.     
  803.     substr($var,0,1) = 'S';
  804.  
  805.     This assumes that $[ is 0;  for a library routine where you can't know
  806.     $[, you should use this instead:
  807.  
  808.     substr($var,$[,1) = 'S';
  809.  
  810.     While it would be slower, you could in this case use a substitute:
  811.  
  812.     $var =~ s/^./S/;
  813.     
  814.     But this won't work if the string is empty or its first character is a
  815.     newline, which "." will never match.  So you could use this instead:
  816.  
  817.     $var =~ s/^[^\0]?/S/;
  818.  
  819.     To do things like translation of the first part of a string, use
  820.     substr, as in:
  821.  
  822.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  823.  
  824.     If you don't know the length of what to translate, something like this
  825.     works: 
  826.  
  827.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  828.     
  829.     For some things it's convenient to use the /e switch of the substitute
  830.     operator: 
  831.  
  832.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  833.  
  834.     although in this case, it runs more slowly than does the previous
  835.     example. 
  836.  
  837.  
  838. 4.23) Can I use Perl regular expressions to match balanced text?
  839.  
  840.     No, or at least, not by themselves.
  841.  
  842.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  843.     strictly regular because they do backreferencing (the \1 notation), you
  844.     still can't do it.  You need to employ auxiliary logic.  A simple
  845.     approach would involve keeping a bit of state around, something 
  846.     vaguely like this (although we don't handle patterns on the same line):
  847.  
  848.     while(<>) {
  849.         if (/pat1/) {
  850.         if ($inpat++ > 0) { warn "already saw pat1" } 
  851.         redo;
  852.         } 
  853.         if (/pat2/) {
  854.         if (--$inpat < 0) { warn "never saw pat1" } 
  855.         redo;
  856.         } 
  857.     }
  858.  
  859.     A rather more elaborate subroutine to pull out balanced and possibly
  860.     nested single chars, like ` and ', { and }, or ( and ) can be found
  861.     on convex.com in /pub/perl/scripts/pull_quotes.
  862.  
  863.  
  864. 4.24) What does it mean that regexps are greedy?  How can I get around it?
  865.  
  866.     The basic idea behind regexps being greedy is that they will match the
  867.     maximum amount of data that they can, sometimes resulting in incorrect
  868.     or strange answers.
  869.  
  870.     For example, I recently came across something like this:
  871.  
  872.     $_="this (is) an (example) of multiple parens";
  873.     while ( m#\((.*)\)#g ) {
  874.         print "$1\n";
  875.     }
  876.  
  877.     This code was supposed to match everything between a set of
  878.     parentheses.  The expected output was:
  879.  
  880.     is
  881.     example
  882.  
  883.     However, the backreference ($1) ended up containing "is) an (example",
  884.     clearly not what was intended.
  885.  
  886.     In perl4, the way to stop this from happening is to use a negated
  887.     group.  If the above example is rewritten as follows, the results are
  888.     correct: 
  889.  
  890.     while ( m#\(([^)]*)\)#g ) {
  891.  
  892.     In perl5 there is a new minimal matching metacharacter, '?'.  This
  893.     character is added to the normal metacharacters to modify their
  894.     behaviour, such as "*?", "+?", or even "??".  The example would now be
  895.     written in the following style:
  896.  
  897.     while (m#\((.*?)\)#g )
  898.  
  899.     Hint: This new operator leads to a very elegant method of stripping
  900.     comments from C code:
  901.  
  902.     s:/\*.*?\*/::gs
  903.  
  904.  
  905. 4.25) How do I use a regular expression to strip C style comments from a
  906.       file?
  907.  
  908.     Since we're talking about how to strip comments under perl5, now is a
  909.     good time to talk about doing it in perl4.  The easiest way to strip
  910.     comments in perl4 is to transform the comment close (*/) into something
  911.     that can't be in the string, or is at least extremely unlikely to be in
  912.     the string.  I find \256 (the registered or reserved sign, an R inside
  913.     a circle) is fairly unlikely to be used and is easy to remember.  So,
  914.     our code looks something like this:
  915.  
  916.     s:\*/:\256:g;        # Change all */ to circled R
  917.     s:/\*[^\256]*\256::g;   # Remove everything from \* to circled R
  918.     print;
  919.  
  920.     To ensure that you correctly handle multi-line comments, don't forget 
  921.     to set $* to 1, informing perl that it should do multi-line pattern
  922.     matching. 
  923.  
  924.     [Untested changes.  If it's wrong or you don't understand it, check 
  925.         with Jeff.  If it's wrong, let me know so I can change it. ] 
  926.  
  927.     Jeff Friedl* suggests that the above solution is incorrect.  He says it 
  928.     will fail on imbedded comments and function proto-typing as well as on
  929.     comments that are part of strings.  The following regexp should handle
  930.     everything:  
  931.  
  932.         $/ = undef;
  933.         $_ = <>; 
  934.  
  935.         s#/\*[^*]*\*+([^/*][^*]*\*+)*/|([^/"']*("[^"\\]*(\\[\d\D][^"\\]*)*"[^/"']*|'[^'\\]*(\\[\d\D][^'\\]*)*'[^/"']*|/+[^*/][^/"']*)*)#$2#g;
  936.         print; 
  937.  
  938.  
  939. 4.26) Why doesn't "local($foo) = <FILE>;" work right?
  940.  
  941.     Well, it does.  The thing to remember is that local() provides an array
  942.     context, and that the <FILE> syntax in an array context will read all the
  943.     lines in a file.  To work around this, use:
  944.  
  945.     local($foo);
  946.     $foo = <FILE>;
  947.  
  948.     You can use the scalar() operator to cast the expression into a scalar
  949.     context:
  950.  
  951.     local($foo) = scalar(<FILE>);
  952.  
  953.  
  954. 4.27) How can I detect keyboard input without reading it? 
  955.  
  956.     You should check out the Frequently Asked Questions list in
  957.     comp.unix.* for things like this: the answer is essentially the same.
  958.     It's very system dependent.  Here's one solution that works on BSD
  959.     systems:
  960.  
  961.     sub key_ready {
  962.         local($rin, $nfd);
  963.         vec($rin, fileno(STDIN), 1) = 1;
  964.         return $nfd = select($rin,undef,undef,0);
  965.     }
  966.  
  967.  
  968. 4.28) How can I read a single character from the keyboard under UNIX and DOS?
  969.  
  970.     A closely related question to the no-echo question below is how to
  971.     input a single character from the keyboard.  Again, this is a system
  972.     dependent operation.  The following code may or may not help you.  It
  973.     should work on both SysV and BSD flavors of UNIX:
  974.  
  975.     $BSD = -f '/vmunix';
  976.     if ($BSD) {
  977.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  978.     }
  979.     else {
  980.         system "stty", '-icanon',
  981.         system "stty", 'eol', "\001"; 
  982.     }
  983.  
  984.     $key = getc(STDIN);
  985.  
  986.     if ($BSD) {
  987.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  988.     }
  989.     else {
  990.         system "stty", 'icanon';
  991.         system "stty", 'eol', '^@'; # ascii null
  992.     }
  993.     print "\n";
  994.  
  995.     You could also handle the stty operations yourself for speed if you're
  996.     going to be doing a lot of them.  This code works to toggle cbreak
  997.     and echo modes on a BSD system:
  998.  
  999.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  1000.     local($on) = $_[0];
  1001.     local($sgttyb,@ary);
  1002.     require 'sys/ioctl.ph';
  1003.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  1004.  
  1005.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  1006.  
  1007.     @ary = unpack($sgttyb_t,$sgttyb);
  1008.     if ($on) {
  1009.         $ary[4] |= &CBREAK;
  1010.         $ary[4] &= ~&ECHO;
  1011.     } else {
  1012.         $ary[4] &= ~&CBREAK;
  1013.         $ary[4] |= &ECHO;
  1014.     }
  1015.     $sgttyb = pack($sgttyb_t,@ary);
  1016.  
  1017.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  1018.     }
  1019.  
  1020.     Note that this is one of the few times you actually want to use the
  1021.     getc() function; it's in general way too expensive to call for normal
  1022.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  1023.     or sysread() functions.
  1024.  
  1025.     For perspectives on more portable solutions, use anon ftp to retrieve
  1026.     the file /pub/perl/info/keypress from convex.com.
  1027.  
  1028.     Under Perl5, with William Setzer's Curses module, you can call
  1029.     &Curses::cbreak() and &Curses::nocbreak() to turn cbreak mode on and
  1030.     off.  You can then use getc() to read each character.  This should work
  1031.     under both BSD and SVR systems.  If anyone can confirm or deny
  1032.     (especially William), please contact the maintainers.
  1033.  
  1034.     For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports:
  1035.  
  1036.     To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
  1037.     from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
  1038.     across the net every so often):
  1039.  
  1040.     $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
  1041.     $old_ioctl &= 0xff;
  1042.     ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5
  1043.  
  1044.     Then to read a single character:
  1045.  
  1046.     sysread(STDIN,$c,1);               # Read a single character
  1047.  
  1048.     And to put the PC back to "cooked" mode:
  1049.  
  1050.     ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.
  1051.  
  1052.  
  1053.     So now you have $c.  If ord($c) == 0, you have a two byte code, which
  1054.     means you hit a special key.  Read another byte (sysread(STDIN,$c,1)),
  1055.     and that value tells you what combination it was according to this
  1056.     table:
  1057.  
  1058.     # PC 2-byte keycodes = ^@ + the following:
  1059.  
  1060.     # HEX     KEYS
  1061.     # ---     ----
  1062.     # 0F      SHF TAB
  1063.     # 10-19   ALT QWERTYUIOP
  1064.     # 1E-26   ALT ASDFGHJKL
  1065.     # 2C-32   ALT ZXCVBNM
  1066.     # 3B-44   F1-F10
  1067.     # 47-49   HOME,UP,PgUp
  1068.     # 4B      LEFT
  1069.     # 4D      RIGHT
  1070.     # 4F-53   END,DOWN,PgDn,Ins,Del
  1071.     # 54-5D   SHF F1-F10
  1072.     # 5E-67   CTR F1-F10
  1073.     # 68-71   ALT F1-F10
  1074.     # 73-77   CTR LEFT,RIGHT,END,PgDn,HOME
  1075.     # 78-83   ALT 1234567890-=
  1076.     # 84      CTR PgUp
  1077.  
  1078.     This is all trial and error I did a long time ago, I hope I'm reading the
  1079.     file that worked.
  1080.  
  1081.  
  1082. 4.29) How can I get input from the keyboard without it echoing to the
  1083.       screen?
  1084.  
  1085.     Terminal echoing is generally handled directly by the shell.
  1086.     Therefore, there is no direct way in perl to turn echoing on and off.
  1087.     However, you can call the command "stty [-]echo".  The following will
  1088.     allow you to accept input without it being echoed to the screen, for
  1089.     example as a way to accept passwords (error checking deleted for
  1090.     brevity):
  1091.  
  1092.     print "Please enter your password: ";
  1093.         system("stty -echo");
  1094.     chop($password=<STDIN>);
  1095.     print "\n";
  1096.     system("stty echo");
  1097.  
  1098.     Again, under perl 5, you can use Curses and call &Curses::noecho() and
  1099.     &Curses::echo() to turn echoing off and on.
  1100.  
  1101.  
  1102. 4.30) Is there any easy way to strip blank space from the beginning/end of
  1103.     a string?
  1104.  
  1105.     Yes, there is.  Using the substitution command, you can match the
  1106.     blanks and replace it with nothing.  For example, if you have the
  1107.     string "     String     " you can use this:
  1108.  
  1109.         s/^\s+|\s+$//g;
  1110.  
  1111.     or even
  1112.  
  1113.         s/^\s+//; s/\s+$//;
  1114.  
  1115.     Note however that Jeffrey Friedl* says these are only good for shortish
  1116.     strings.  For longer strings, and worse-case scenarios, they tend to
  1117.     break-down and become inefficient.
  1118.  
  1119.     For the longer strings, he suggests using either
  1120.  
  1121.         $_ = $1 if m/^\s*((.*\S)?)/;
  1122.  
  1123.     or
  1124.     
  1125.         s/^\s*((.*\S)?)\s*$/$1/;
  1126.  
  1127.     It should also be noted that for generally nice strings, these tend to
  1128.     be noticably slower than the simple ones above.  It is suggested that
  1129.     you use whichever one will fit your situation best, understanding that
  1130.     the first examples will work in roughly ever situation known even if
  1131.     slow at times.
  1132. --
  1133. Stephen P Potter        spp@vx.com        Varimetrix Corporation
  1134. 2350 Commerce Park Drive, Suite 4                Palm Bay, FL 32905
  1135. (407) 676-3222                           CAD/CAM/CAE/Software
  1136.